package com.hmall.item.listener;

import cn.hutool.json.JSONUtil;
import com.hmall.common.constant.ESConstants;
import com.hmall.common.constant.MQConstants;
import com.hmall.item.domain.po.ItemDoc;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 勾新杰
 * @version 1.0
 * @date 2024/10/31 19:52
 */
@Component
@RequiredArgsConstructor
public class UpdateItemDocListener {

    private final RestHighLevelClient client;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.ITEM_UPDATE_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MQConstants.ITEM_EXCHANGE_DIRECT_NAME),
            key = MQConstants.ITEM_UPDATE_ROUTING_KEY
    ))
    public void updateStatus(ItemDoc itemDoc) throws IOException {
        IndexRequest request = new IndexRequest(ESConstants.INDEX_NAME).id(String.valueOf(itemDoc.getId()));
        request.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }
}
